package com.ftg.learn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ftg.learn.entity.Product;
import com.ftg.learn.mapper.ProductMapper;
import com.ftg.learn.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.util.PageEx;
import com.ftg.learn.util.PageUtils;
import com.ftg.learn.util.R;
import com.ftg.learn.util.RedisUtils;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 布衣
 * @since 2025-07-22
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    private final Lock lock = new ReentrantLock();

    private final String KEY_PREFIX = "product:*";

    @Resource
    RedisUtils redisUtils;

    @Override
    public R<String> list(String name, Integer page, Integer size) {
        lock.lock();
        String key = "product:list:" + name + ":" + page + ":" + size;
        try {
            if (redisUtils.existsByKey(key)) {
                PageHelper.startPage(page, size);
                QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

                if (null != name && !name.isEmpty()) {
                    queryWrapper.likeRight("name", name);
                }

                PageInfo<Product> pageInfo = new PageInfo<>(this.list(queryWrapper));

                String jsonString = JSON.toJSONString(PageUtils.convertToPageEx(pageInfo, page, size));
                redisUtils.setValueByKey(key, jsonString);
            }
            return R.ok(redisUtils.getValueByKey(key));
        } catch (Exception e) {
            return R.failure();
        } finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> add(@RequestBody Product product){
        if(this.save(product)){
            redisUtils.deleteByKey(KEY_PREFIX);
        }
        return R.ok(true);
    }
}
